from django.shortcuts import render
from django.views.generic import TemplateView
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import NavigationGroup, NavigationLink
from .serializers import NavigationGroupSerializer, NavigationLinkSerializer

# Create your views here.

class NavigationView(TemplateView):
    """导航首页视图"""
    template_name = 'navigation/index.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 获取所有导航分组及其链接
        groups = NavigationGroup.objects.all().order_by('order')
        
        # 预处理数据，为每个分组添加其链接列表
        processed_groups = []
        for group in groups:
            # 获取该分组下的所有活跃链接
            links = group.links.filter(is_active=True).order_by('order')
            # 创建包含分组信息和链接列表的字典
            processed_group = {
                'id': group.id,
                'title': group.title,
                'order': group.order,
                'links': links
            }
            processed_groups.append(processed_group)
            
        context['groups'] = processed_groups
        return context

class NavigationGroupViewSet(viewsets.ModelViewSet):
    """导航分组 API 视图集"""
    queryset = NavigationGroup.objects.all()
    serializer_class = NavigationGroupSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    search_fields = ['title']
    ordering_fields = ['order', 'created_at']
    ordering = ['order']

class NavigationLinkViewSet(viewsets.ModelViewSet):
    """导航链接 API 视图集"""
    queryset = NavigationLink.objects.filter(is_active=True)
    serializer_class = NavigationLinkSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    search_fields = ['name', 'url', 'description']
    filterset_fields = ['group']
    ordering_fields = ['order', 'created_at']
    ordering = ['order']
